package cn.qianxun.meta.quartz.service.impl;

import cn.qianxun.meta.common.core.dto.RowsData;
import cn.qianxun.meta.quartz.service.IXxlJobLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import cn.qianxun.meta.quartz.domain.XxlJobLog;
import cn.qianxun.meta.quartz.dto.XxlJobLogQueryDTO;
import cn.qianxun.meta.quartz.mapper.XxlJobLogMapper;
import cn.qianxun.meta.quartz.vo.XxlJobLogVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author fuzhilin
 * @Date 2023/9/8 16:57
 * @Description
 */
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Transactional(readOnly = false, rollbackFor = {Exception.class, RuntimeException.class}, propagation = Propagation.REQUIRES_NEW)
//开启新事务
public class XxlJobLogServiceImpl extends ServiceImpl<XxlJobLogMapper, XxlJobLog> implements IXxlJobLogService {
    private final XxlJobLogMapper xxlJobLogMapper;

    @Override
    public RowsData<XxlJobLogVO> getXxlJobLogs(XxlJobLogQueryDTO dto) {
        try (Page<Object> page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize())) {
            List<XxlJobLog> xxlJobLogs = xxlJobLogMapper.getXxlJobLogs(dto);
            List<XxlJobLogVO> list = xxlJobLogs.stream().map(xxlJobLog -> {
                XxlJobLogVO jobLogVO = new XxlJobLogVO();
                BeanUtils.copyProperties(xxlJobLog, jobLogVO);
                return jobLogVO;
            }).collect(Collectors.toList());
            return new RowsData<XxlJobLogVO>(list, page.getTotal(), dto.getPageNum());
        }
    }

    @Override
    public int clearLog(List<String> logIds) {
        return xxlJobLogMapper.clearLog(logIds);
    }

    @Override
    public int updateHandleInfo(XxlJobLog xxlJobLog) {
        return xxlJobLogMapper.updateHandleInfo(xxlJobLog);
    }

    @Override
    public int updateTriggerInfo(XxlJobLog xxlJobLog) {
        return xxlJobLogMapper.updateTriggerInfo(xxlJobLog);
    }

    @Override
    public int delLogByJobId(String jobId) {
        return xxlJobLogMapper.delLogByJobId(jobId);
    }

    @Override
    public int delLogGlueByJobId(String jobId) {
        return xxlJobLogMapper.delLogGlueByJobId(jobId);
    }
}
